"""
    Author:
    Date: 2018-12-25

    微信管理后台-统计页面
"""
import datetime

from django.shortcuts import render

from entities import call_mgr
from entities import pay_mgr
from entities import server_mgr
from entities import user_mgr

from .. import helpers
from .. helpers import gma_login_required
from entities.consts import *
from utils import util


@gma_login_required
def index(request):
    """ 统计首页 """
    today_begin_time, today_end_time = util.get_today_interval()

    context = helpers.build_context(request)
    # 今日累计新增用户数量
    context['today_new_user_count'] = user_mgr.get_new_user_count(today_begin_time, today_end_time, request=request)
    # 今日iOS新增用户数量
    context['today_ios_new_user_count'] = user_mgr.get_ios_new_user_count(today_begin_time, today_end_time)
    # 今日Android新增用户数量
    context['today_and_new_user_count'] = user_mgr.get_android_new_user_count(today_begin_time, today_end_time)

    # 今日充值金额数量
    context['today_pay_amount'] = user_mgr.get_pay_amount(today_begin_time, today_end_time, request=request)
    # 今日通话次数
    context['today_call_count'] = call_mgr.get_call_count(today_begin_time, today_end_time, request=request)
    # 今日通话时长
    context['today_call_seconds'] = call_mgr.get_call_seconds(today_begin_time, today_end_time, request=request)

    # 用户总数
    context['total_user_count'] = user_mgr.get_total_user_count()
    # 主播总数
    context['total_broadcaster_count'] = user_mgr.get_total_broadcaster_count(request=request)

    # 累计视频通话收益
    context['total_vchat_income'] = pay_mgr.get_income_amount_with_type(TICKET_INPUT_VIDEO_CHAT, '', today_end_time)
    # 累计短视频收益
    context['total_video_income'] = pay_mgr.get_income_amount_with_type(TICKET_INPUT_SELL_VIDEO, '', today_end_time)
    # 累计私信收益
    context['total_message_income'] = pay_mgr.get_income_amount_with_type(TICKET_INPUT_RECEIVE_MESSAGE, '', today_end_time)
    # 累计礼物收益
    context['total_gift_income'] = pay_mgr.get_income_amount_with_type(TICKET_INPUT_RECEIVE_GIFT, '', today_end_time)

    # 累计充值金额
    context['total_pay_amount'] = user_mgr.get_pay_amount('', today_end_time, request)

    # 钻石预测数据
    context['diamond_detail'] = pay_mgr.get_diamond_stat_detail()

    # ----------------------------------
    # 本周数据统计
    # ----------------------------------
    days = 7
    begin_time = util.datetimetostr(datetime.date.today() - datetime.timedelta(days=days))
    end_time = util.datetimetostr(datetime.date.today() + datetime.timedelta(days=1))
    paid_new_user_count = user_mgr.get_paid_new_user_count(begin_time, end_time)
    new_caster_count = user_mgr.get_new_caster_count(begin_time, end_time)
    # 需要排除的假量新增用户
    excluded_new_user_count = user_mgr.get_new_user_count_of_channel_ex('t1', begin_time, end_time)
    new_user_count = user_mgr.get_new_user_count(begin_time, end_time, request=request) - new_caster_count - excluded_new_user_count
    paid_amount = user_mgr.get_new_user_pay_amount(begin_time, end_time)

    # 近期新增用户
    context['new_user_count'] = new_user_count
    # 近期新增主播
    context['new_caster_count'] = new_caster_count
    # 近期充值新增用户
    context['paid_new_user_count'] = paid_new_user_count
    # PUR
    context['pur'] = '%.2f' % ((100*paid_new_user_count/new_user_count) if new_user_count > 0 else 0)
    # 近期充值金额
    context['paid_amount'] = paid_amount
    # ARPU
    context['arpu'] = '%.2f' % ((paid_amount/new_user_count) if new_user_count > 0 else 0)
    # ARPPU
    context['arppu'] = '%.2f' % (int(paid_amount/paid_new_user_count) if paid_new_user_count > 0 else 0)

    return render(request, 'gma/stat/stat.html', context)


@gma_login_required
def archive_stat_data(request, begin_time, end_time):
    context = helpers.build_context(request)
    context['begin_time'] = begin_time
    context['end_time'] = end_time

    paid_new_user_count = user_mgr.get_paid_new_user_count(begin_time, end_time)
    new_caster_count = user_mgr.get_new_caster_count(begin_time, end_time)

    # 需要排除的假量新增用户
    excluded_new_user_count = user_mgr.get_new_user_count_of_channel_ex('t1', begin_time, end_time)
    new_user_count = user_mgr.get_new_user_count(begin_time, end_time, request=request) - new_caster_count - excluded_new_user_count
    paid_amount = user_mgr.get_new_user_pay_amount(begin_time, end_time)

    # new_user_count = int(new_user_count*0.8)
    # paid_new_user_count = int(paid_new_user_count*0.8)

    # 近期新增用户
    context['new_user_count'] = new_user_count
    # 近期新增主播
    context['new_caster_count'] = new_caster_count
    # 近期充值新增用户
    context['paid_new_user_count'] = paid_new_user_count
    # PUR
    context['pur'] = '%.2f' % ((100*paid_new_user_count/new_user_count) if new_user_count > 0 else 0)
    # 近期充值金额
    context['paid_amount'] = paid_amount
    # ARPU
    context['arpu'] = '%.2f' % ((paid_amount/new_user_count) if new_user_count > 0 else 0)
    # ARPPU
    context['arppu'] = '%.2f' % (int(paid_amount/paid_new_user_count) if paid_new_user_count > 0 else 0)

    return render(request, 'gma/stat/archive_stat.html', context)


@gma_login_required
def diamond_detail(request):
    """ 钻石数量分析 """
    detail = pay_mgr.get_diamond_stat_detail()

    context = helpers.build_context(request)
    context['data'] = detail
    return render(request, 'gma/stat/diamond_detail.html', context)


@gma_login_required
def pay_chart_detail(request):
    context = helpers.build_context(request)
    data = pay_mgr.get_daily_pay_amount(15, request=request)
    data = [(x['d'], x['total_amount'], '元') for x in data]

    context['data'] = data
    context['data_label'] = '充值金额'
    context['data_title'] = '每日充值金额趋势图'
    return render(request, 'gma/stat/chart_detail_pay.html', context)


@gma_login_required
def pay_detail(request, begin, end):
    """ 指定时间范围内的充值列表 """
    if begin == end and len(begin) == len('2019-01-01'):
        end = end + ' 23:59:59'

    logs = pay_mgr.get_recharge_list_by_time(begin, end, request=request)
    for log in logs:
        log['recharge_type_desp'] = get_recharge_type_desp(log['type'])

    context = helpers.build_context(request)
    context['logs'] = logs
    context['begin_time'] = begin
    context['end_time'] = end
    return render(request, 'gma/stat/pay_detail.html', context)


@gma_login_required
def consume_detail(request, begin, end):
    """ 指定时间范围内的消耗列表 """
    if begin == end and len(begin) == len('2019-01-01'):
        end = end + ' 23:59:59'

    logs = user_mgr.get_diamond_consume_list_by_time(begin, end, request)

    context = helpers.build_context(request)
    context['logs'] = logs
    context['begin_time'] = begin
    context['end_time'] = end
    return render(request, 'gma/stat/consume_detail.html', context)


@gma_login_required
def devkeep_consume_detail(request, begin, end):
    """ 指定时间范围内的消耗列表 """
    if begin == end and len(begin) == len('2019-01-01'):
        end = end + ' 23:59:59'

    logs = user_mgr.get_devkeep_diamond_consume_list_by_time(begin, end)

    context = helpers.build_context(request)
    context['logs'] = logs
    context['begin_time'] = begin
    context['end_time'] = end
    return render(request, 'gma/stat/consume_detail.html', context)


@gma_login_required
def new_user_chart_detail(request):
    """ 新增用户的统计详情 """
    data = user_mgr.get_daily_new_user_count(15, request=request)
    data = [(x['d'], x['total_count'], '人') for x in data]

    context = helpers.build_context(request)
    context['data'] = data
    context['data_label'] = '新增用户'
    context['data_title'] = '每日新增用户趋势图'
    return render(request, 'gma/stat/chart_detail_new_user.html', context)


@gma_login_required
def call_count_chart_detail(request):
    data = call_mgr.get_daily_call_count(15, request=request)
    data = [(x['d'], x['total_count'], '次') for x in data]

    context = helpers.build_context(request)
    context['data'] = data
    context['data_label'] = '通话次数'
    context['data_title'] = '每日通话次数趋势图'
    return render(request, 'gma/stat/chart_detail_call_count.html', context)


@gma_login_required
def call_seconds_chart_detail(request):
    data = call_mgr.get_daily_call_count(15, request=request)
    data = [(x['d'], x['total_seconds'], '秒') for x in data]

    context = helpers.build_context(request)
    context['data'] = data
    context['data_label'] = '通话时长'
    context['data_title'] = '每日通话时长趋势图'
    return render(request, 'gma/stat/chart_detail_call_seconds.html', context)


@gma_login_required
def call_detail(request, begin, end):
    """ 指定时间范围内的充值列表 """
    if begin == end and len(begin) == len('2019-01-01'):
        end = end + ' 23:59:59'

    logs = user_mgr.get_call_records_by_time(begin, end, request=request)
    context = helpers.build_context(request)
    context['logs'] = logs
    context['begin_time'] = begin
    context['end_time'] = end
    return render(request, 'gma/stat/call_detail.html', context)


@gma_login_required
def new_user_detail(request, begin, end):
    """ 指定时间范围内的新增用户列表 """
    if begin == end and len(begin) == len('2019-01-01'):
        end = end + ' 23:59:59'

    casters = user_mgr.get_new_users_by_time(begin, end, request=request)
    context = helpers.build_context(request)
    context['casters'] = casters
    context['total_count'] = user_mgr.get_new_user_count_by_time(begin, end, request=request)
    context['begin_time'] = begin
    context['end_time'] = end
    return render(request, 'gma/caster/caster_list.html', context)


@gma_login_required
def daily_list(request, subject):
    """ 逐日分析 """
    context = helpers.build_context(request)
    context['data'] = util.get_last_days_info(15)
    context['subject'] = subject
    return render(request, 'gma/stat/daily_list.html', context)


@gma_login_required
def subject_analysis(request, subject, begin, end):
    """ 主题分析 """
    subject = int(subject)
    if subject == SUBJECT_NU_AND_ONLINE_CASTER_COUNT:
        data_title = '新增用户 & 主播数量关系对比图'
        data_labels = ['新增用户', '在线主播数']
        data = []
        data1 = server_mgr.get_new_user_count_per_hour(begin, end)
        data2 = server_mgr.get_online_caster_count_per_hour(begin, end)
        for h in range(24):
            v1 = data1.get(h, 0)
            v2 = data2.get(h, 0)
            data.append((f'{begin[:10]} {h:02d}:00', v1, v2))
    elif subject == SUBJECT_NU_AND_CALL_COUNT:
        data_title = '新增用户 & 通话次数关系对比图'
        data_labels = ['新增用户', '通话次数']
        data = []
        data1 = server_mgr.get_new_user_count_per_hour(begin, end)
        data2 = server_mgr.get_call_count_per_hour(begin, end, request=request)
        for h in range(24):
            v1 = data1.get(h, 0)
            v2 = data2.get(h, 0)
            data.append((f'{begin[:10]} {h:02d}:00', v1, v2))
    else:
        return helpers.show_page_tips(request, f'无效的主题id: {subject}')

    context = helpers.build_context(request)
    context['data_title'] = data_title
    context['data_labels'] = data_labels
    context['data'] = data
    return render(request, 'gma/stat/chart2_detail.html', context)


@gma_login_required
def fake_detect(request):
    """ 用户行为分析首页 """
    channels = user_mgr.get_channels()
    channels.sort()
    today = util.datetimetostr(datetime.date.today())[:10]

    context = helpers.build_context(request)
    context['channels'] = channels
    context['days'] = util.get_last_days_info(15)
    context['data_title'] = ''
    return render(request, 'gma/stat/fake.html', context)


@gma_login_required
def fake_detail(request, channel, day):
    """ 用户行为分析详情页"""
    # 新增用户数量
    new_user_count = user_mgr.get_new_user_count_of_channel(channel, day)
    # 新增累计在线时长
    total_online_seconds = user_mgr.get_new_users_total_online_seconds_of_channel(channel, day)
    # 新增用户平均在线时长
    average_online_seconds = int(total_online_seconds/new_user_count) if new_user_count > 0 else 0

    # 新增付费用户数量
    new_pay_user_count = user_mgr.get_new_pay_user_count_of_channel(channel, day)
    # 新增用户充值数量
    pay_amount = user_mgr.get_new_user_total_pay_amount_of_channel(channel, day)

    # 新增赠送礼物用户数量
    send_gift_new_user_count = user_mgr.get_new_consume_user_count_of_channel(channel, day, DIAMOND_OUTPUT_SEND_GIFT)
    # 新增购买短视频用户数量
    buy_video_new_user_count = user_mgr.get_new_consume_user_count_of_channel(channel, day, DIAMOND_OUTPUT_BUY_VIDEO)
    # 新增视频通话用户数量
    video_chat_new_user_count = user_mgr.get_new_consume_user_count_of_channel(channel, day, DIAMOND_OUTPUT_VIDEO_CHAT)
    # 新增发送私信用户数量
    send_message_new_user_count = user_mgr.get_new_consume_user_count_of_channel(channel, day, DIAMOND_OUTPUT_SEND_MESSAGE)
    # 新增消费用户数量
    consume_new_user_count = send_gift_new_user_count + buy_video_new_user_count + video_chat_new_user_count + send_message_new_user_count

    # 关注主播的用户数量
    follow_caster_new_user_count = user_mgr.get_follow_caster_new_user_count(channel, day)
    # 屏蔽主播的用户数量
    ban_caster_new_user_count = user_mgr.get_ban_caster_new_user_count(channel, day)
    # 拨打电话的新增用户数量
    call_caster_new_user_count = user_mgr.get_call_caster_new_user_count(channel, day)

    context = helpers.build_context(request)
    context['channel'] = channel
    context['day'] = day

    # 登录情况分析
    context['new_user_count'] = new_user_count
    context['average_online_seconds'] = average_online_seconds

    # 充值分析
    context['new_pay_user_count'] = new_pay_user_count
    context['pay_amount'] = pay_amount
    context['ARPU'] = (pay_amount/new_user_count) if new_user_count > 0 else 0
    context['ARPPU'] = (pay_amount/new_pay_user_count) if new_pay_user_count > 0 else 0
    # 付费渗透率
    context['PUR'] = (100*new_pay_user_count/new_user_count) if new_user_count > 0 else 0

    # 消费分析
    context['send_gift_new_user_count'] = send_gift_new_user_count
    context['buy_video_new_user_count'] = buy_video_new_user_count
    context['video_chat_new_user_count'] = video_chat_new_user_count
    context['send_message_new_user_count'] = send_message_new_user_count
    context['consume_ratio'] = (100*consume_new_user_count/new_user_count) if new_user_count > 0 else 0 # 主播关注率

    # 交互分析
    context['follow_caster_new_user_count'] = follow_caster_new_user_count
    context['caster_follow_ratio'] = (100*follow_caster_new_user_count/new_user_count) if new_user_count > 0 else 0 # 主播关注率
    context['ban_caster_new_user_count'] = ban_caster_new_user_count
    context['call_caster_new_user_count'] = call_caster_new_user_count

    return render(request, 'gma/stat/fake_detail.html', context)


if __name__ == '__main__':
    print('ok')
